import moment from "moment";
export const forEach = (arr, fn) => {
    if (!arr.length || !fn) return
    let i = -1
    let len = arr.length
    while (++i < len) {
        let item = arr[i]
        fn(item, i, arr)
    }
}

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @description 得到两个数组的交集, 两个数组的元素为数值或字符串
 */
export const getIntersection = (arr1, arr2) => {
    let len = Math.min(arr1.length, arr2.length)
    let i = -1
    let res = []
    while (++i < len) {
        const item = arr2[i]
        if (arr1.indexOf(item) > -1) res.push(item)
    }
    return res
}

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @description 得到两个数组的并集, 两个数组的元素为数值或字符串
 */
export const getUnion = (arr1, arr2) => {
    return Array.from(new Set([...arr1, ...arr2]))
}

/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
 */
export const hasOneOf = (targetarr, arr) => {
    return targetarr.some(_ => arr.indexOf(_) > -1)
}


/**
 * @param {String|Number} value 要验证的字符串或数值
 * @param {*} validList 用来验证的列表
 */
export function oneOf(value, validList) {
    for (let i = 0; i < validList.length; i++) {
        if (value === validList[i]) {
            return true
        }
    }
    return false
}

/**
 * @param {Number} timeStamp 判断时间戳格式是否是毫秒
 * @returns {Boolean}
 */
const isMillisecond = timeStamp => {
    const timeStr = String(timeStamp)
    return timeStr.length > 10
}

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} currentTime 当前时间时间戳
 * @returns {Boolean} 传入的时间戳是否早于当前时间戳
 */
const isEarly = (timeStamp, currentTime) => {
    return timeStamp < currentTime
}

/**
 * @param {Number} num 数值
 * @returns {String} 处理后的字符串
 * @description 如果传入的数值小于10，即位数只有1位，则在前面补充0
 */
const getHandledValue = num => {
    return num < 10 ? '0' + num : num
}

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} startType 要返回的时间字符串的格式类型，传入'year'则返回年开头的完整时间
 */
const getDate = (timeStamp, startType) => {
    const d = new Date(timeStamp * 1000)
    const year = d.getFullYear()
    const month = getHandledValue(d.getMonth() + 1)
    const date = getHandledValue(d.getDate())
    const hours = getHandledValue(d.getHours())
    const minutes = getHandledValue(d.getMinutes())
    const second = getHandledValue(d.getSeconds())
    let resStr = ''
    if (startType === 'year') resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second
    else resStr = month + '-' + date + ' ' + hours + ':' + minutes
    return resStr
}

/**
 * @param {String|Number} timeStamp 时间戳
 * @returns {String} 相对时间字符串
 */
export const getRelativeTime = timeStamp => {
    // 判断当前传入的时间戳是秒格式还是毫秒
    const IS_MILLISECOND = isMillisecond(timeStamp)
    // 如果是毫秒格式则转为秒格式
    if (IS_MILLISECOND) Math.floor(timeStamp /= 1000)
    // 传入的时间戳可以是数值或字符串类型，这里统一转为数值类型
    timeStamp = Number(timeStamp)
    // 获取当前时间时间戳
    const currentTime = Math.floor(Date.parse(new Date()) / 1000)
    // 判断传入时间戳是否早于当前时间戳
    const IS_EARLY = isEarly(timeStamp, currentTime)
    // 获取两个时间戳差值
    let diff = currentTime - timeStamp
    // 如果IS_EARLY为false则差值取反
    if (!IS_EARLY) diff = -diff
    let resStr = ''
    const dirStr = IS_EARLY ? '前' : '后'
    // 少于等于59秒
    if (diff <= 59) resStr = diff + '秒' + dirStr
    // 多于59秒，少于等于59分钟59秒
    else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr
    // 多于59分钟59秒，少于等于23小时59分钟59秒
    else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr
    // 多于23小时59分钟59秒，少于等于29天59分钟59秒
    else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr
    // 多于29天59分钟59秒，少于364天23小时59分钟59秒，且传入的时间戳早于当前
    else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp)
    else resStr = getDate(timeStamp, 'year')
    return resStr
}

/**
 * @returns {String} 当前浏览器名称
 */
export const getExplorer = () => {
    const ua = window.navigator.userAgent
    const isExplorer = (exp) => {
        return ua.indexOf(exp) > -1
    }
    if (isExplorer('MSIE')) return 'IE'
    else if (isExplorer('Firefox')) return 'Firefox'
    else if (isExplorer('Chrome')) return 'Chrome'
    else if (isExplorer('Opera')) return 'Opera'
    else if (isExplorer('Safari')) return 'Safari'
}

/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function () {
    if (document.addEventListener) {
        return function (element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false)
            }
        }
    } else {
        return function (element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on' + event, handler)
            }
        }
    }
})()

/**
 * @description 解绑事件 off(element, event, handler)
 */
export const off = (function () {
    if (document.removeEventListener) {
        return function (element, event, handler) {
            if (element && event) {
                element.removeEventListener(event, handler, false)
            }
        }
    } else {
        return function (element, event, handler) {
            if (element && event) {
                element.detachEvent('on' + event, handler)
            }
        }
    }
})()

/**
 * 判断一个对象是否存在key，如果传入第二个参数key，则是判断这个obj对象是否存在key这个属性
 * 如果没有传入key这个参数，则判断obj对象是否有键值对
 */
export const hasKey = (obj, key) => {
    if (key) return key in obj
    else {
        let keysArr = Object.keys(obj)
        return keysArr.length
    }
}

/**
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 * @description 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 */
export const objEqual = (obj1, obj2) => {
    const keysArr1 = Object.keys(obj1)
    const keysArr2 = Object.keys(obj2)
    if (keysArr1.length !== keysArr2.length) return false
    else if (keysArr1.length === 0 && keysArr2.length === 0) return true
    /* eslint-disable-next-line */
    else return !keysArr1.some(key => obj1[key] != obj2[key])
}


/**
 * @param [function] 需要防抖的函数
 * @param [number] 毫秒，防抖期限值
 * @description 防抖
 * 厂景：search搜索联想，用户在不断输入值时，用防抖来节约请求资源。window触发resize的时候，不断的调整浏览器窗口大小会不断的触发这个事件，用防抖来让其只触发一次
 */
export const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer) //进入该分支语句，说明当前正在一个计时过程中，并且又触发了相同事件。所以要取消当前的计时，重新开始计时
            timer = setTimeout(() => {
                fn()
            }, delay)
        } else {
            timer = setTimeout(() => {
                fn()
            }, delay) // 进入该分支说明当前并没有在计时，那吗就开始一个计时
        }
    }
}


/**
 * @param [function] 需要节流的函数
 * @param [number] 毫秒，节流期限值
 * @description 节流
 * 厂景：鼠标不断点击触发，mousedown(单位时间内只触发一次) 监听滚动事件，比如是否滑到底部自动加载更多，用throttle来判断
 */
export const throttle = (fn, delay) => {
    let valid = false;
    return function () {
        if (!valid) {
            return false
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false
        setTimeout(() => {
            fn()
            valid = true;
        }, delay)
    }
}


export const extend = (obj1, obj2) => {
    for (let k in obj1) {
        if (obj2[k] != undefined) obj1[k] = obj2[k]
    }
    return obj1
}

/**
 * 生成时间列表
 * @param startDate 开始时间
 * @param endDate 结束时间
 * @param dateTytpe 时间类型
 * @param size  步长
 * @param format 时间格式
 * @returns {[]}
 */
export const listDate = (startDate, endDate, dateTytpe, format) => {
    var listDate1 = [];
    format = format || 'YYYY-MM-DD';
    dateTytpe = dateTytpe || 'day'
    startDate = moment(startDate);
    endDate = endDate ? moment(endDate) : moment();
    var dateLength = Math.abs(startDate.diff(endDate, dateTytpe));
    listDate1.push(startDate.format(format))
    for (var i = 0; i < dateLength; i++) {
        listDate1.push(startDate.add(1, dateTytpe).format(format))
    }
    return listDate1
}
/**
 * 手机号正则校验
 */
export const checkPhoneNumber = (phoneNumber) => {
    var regexp = /^((1[3,5,6,7,8,9][0-9])|(14[5,7])|(17[0,6,7,8])|(19[1,7]))\d{8}$/
    return regexp.test(phoneNumber)
};
/**
 * 校验不可输入中文
 */
export const checkCode = (code) => {
    var regexp = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g
    return regexp.test(code)
};


export class sl_socket {
    constructor(wsUrl, onMsg, onOpen) {
        this.lockSocket = false;
        this.wsUrl = wsUrl;
        this.timeoutObj = null;
        this.reconnectTimeoutObj = null;
        this.socket = null;
        this.onOpen = onOpen
        this.onMsg = onMsg
        this.getWebSocket()
    }

    getWebSocket() {
        let that = this;
        this.socket = new WebSocket(this.wsUrl);
        this.socket.onerror = function () {
            console.log('websocket服务出错了');
            that.reconnect();
        };
        this.socket.onclose = function () {
            console.log('websocket服务关闭了');
            that.reconnect();
        };
        this.socket.onopen = function () {
            that.heartBeat()
            that.onOpen && that.onOpen(that.socket)
        };

        this.socket.onmessage = function (event) {
            that.onMsg && that.onMsg(event.data)
        };
    }


    send(data) {
        this.socket.send(data)
    }

    reconnect() {
        let that = this;
        if (that.lockSocket) return;
        that.lockSocket = true;
        //没连接上会一直重连，设置延迟避免请求过多
        that.reconnectTimeoutObj = setTimeout(function () {

            that.getWebSocket();
            that.lockSocket = false;
        }, 1000);
    }

    close() {
        this.lockSocket = true;
        clearInterval(this.reconnectTimeoutObj);
        clearInterval(this.timeoutObj);
        this.socket.close()
    }

    heartBeat() {
        let that = this;
        this.timeoutObj = setInterval(() => {
            that.socket.send(JSON.stringify({cmd: "heart"}))
        }, 10000)
    }


}


export const getBase64 = (file) => {
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
            imgResult = reader.result;
        };
        reader.onerror = function (error) {
            reject(error);
        };
        reader.onloadend = function () {
            resolve(imgResult);
        };
    });
}

